﻿using System.Linq;
using CardPlay.Model.CardModel;
using CardPlay.Model.GameModel;
using CardPlay.Model.GameModel.Actions;
using CardPlay.Model.GameModel.Presentation;

namespace CardPlay.DemoPack.Games.CongressVariants
{
    // TODO: waste pile shouldn't spread top!
    [Game("2C3285DE-3B71-41BD-94ED-72C69F3CB3E3", LevelOfDifficulty.Easy, LevelOfSkill.ModerateSkill, DurationOfPlay.Within5To10Minutes, NumberOfDecks = 2, Family = FamilyName)]
    public class Alhambra : Congress
    {
        public Alhambra()
        {
            var tableauStyle = StandardStyles.Tableau;
            tableauStyle.EmptyCue = null;

            DefaultTableauStyle = tableauStyle;
            MaximumDeals = 3;
            TableauBuildSequence = CardFaceSequence.SameSuitAdjacentRank;
        }

        protected override void PrepareDealScript(DealScript script)
        {
            script.DealAcesTo(StandardPileNames.Foundations.Take(4));
            script.DealRankTo(StandardPileNames.Foundations.Skip(4).Take(4), Rank.King);

            foreach (var name in NamesOfTableaus)
                script.Deal("3 down;1 up").To(name);

            script.DealRemainingFaceDownTo(Stock);
        }

        protected override bool AllowedToPickupAtTableau(RemovePileAction action)
        {
            return action.Location.Matches(AnyTableau) && action.IsActingOnFaceUpTopCard();
        }

        protected override void OverridePlayingRules(PlayingRules playingRules)
        {
            playingRules.Permit<MovePileAction>().When(BuildIsAllowed);
        }

        protected bool BuildIsAllowed(MovePileAction action)
        {
            return
                action.Location.Matches(AnyFoundation) ?
                    AllowedToBuildFoundation(action) :
                action.Location.Matches(Waste) ?
                    !action.TargetPile.IsEmpty && action.IsBuildingSingleCardSameSuitUpOrDown() :
                false;
        }

        protected override bool AllowedToBuildFoundation(MovePileAction action)
        {
            return action.IsBuildingTwoDeckFoundation();
        }

        protected override void OnTransactionEnding()
        {
            this.FlipFaceDownTopCardsInPilesMatching(AnyTableau);
        }
    }
}